<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天界面</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; margin-bottom: 10px; }
        input, button { margin: 5px; }
    </style>
</head>
<body>
<h2>聊天界面</h2>
<input type="text" id="targetUser" placeholder="输入目标用户名...">
<input type="text" id="message" placeholder="输入消息...">
<button id="sendBtn">发送</button>
<div id="messages"></div>
<img src="https://c-ssl.duitang.com/uploads/item/202003/27/20200327141738_ulbvu.jpg" alt="">
<script>
    const username = prompt("请输入您的用户名:"); // 获取当前用户的用户名
    const socket = new WebSocket(`ws://127.0.0.1:8088/singleChat/${username}`);

    socket.onopen = function() {
        console.log(`${username} 已连接`);
    };

    socket.onmessage = function(event) {
        const messagesDiv = document.getElementById("messages");
        messagesDiv.innerHTML += `<p>${event.data}</p>`;
        messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
    };

    document.getElementById("sendBtn").onclick = function() {
        const targetUser = document.getElementById("targetUser").value;
        const messageInput = document.getElementById("message").value;
        const message = `${targetUser}:text:${messageInput}`; // 格式化消息
        socket.send(message);

        // 显示自己发送的消息
        const messagesDiv = document.getElementById("messages");
        messagesDiv.innerHTML += `<p>我: ${messageInput}</p>`;
        messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部

        document.getElementById("message").value = "";  // 清空输入框
    };
</script>
</body>
</html>
